package com.wonders.hs.pd.mm.web.controller;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author banglong
 * @date 2017/3/6
 */
@Controller
public class FileUploadController {

  /**
   * 文件上传
   */
  @ResponseBody
  @RequestMapping("/fileupload")
  public String fileupload(@RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
      try {
        // todo spring 中获取static目录的绝佳方式
        Resource resource = new ClassPathResource("static/files");
        System.out.print(resource.getFile().getPath() + File.separator + file.getOriginalFilename());
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(resource.getFile().getPath() + File.separator + file.getOriginalFilename()));
        out.write(file.getBytes());
        out.flush();
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
        return "上传失败," + e.getMessage();
      }
      return "上传成功";
    } else {
      return "上传失败，因为文件是空的.";
    }
  }
}
